<!-- src/components/sidebar/Sidebar.vue -->
<template>
  <div class="sidebar-wrapper">
    <el-aside :width="sidebarWidth" class="sidebar">
      <el-container :class="['sidebar-container', { 'sidebar-closed': !isSidebarOpen }]">
        <SidebarHeader 
          :is-sidebar-open="isSidebarOpen"
          @toggle="toggleSidebar"
        />
        <el-main v-show="isSidebarOpen" class="sidebar-main">
          <FilterSection 
            ref = "filterSectionRef"
            @filter-change="handleFilterChange"
            @spots-recommended="handleSpotsRecommended"
            @auto-import-spots="handleAutoImportSpots"
          />
          <SpotList ref="spotListRef"
          :map-loaded="props.mapLoaded"
          @addSpot="addSpot"
          />
        </el-main>
      </el-container>
    </el-aside>

    <PlanningDrawer 
      ref="planningDrawerRef"
      :map-ref="props.mapRef"
      :is-open="isPlanningDrawerOpen"
      :sidebar-open="isSidebarOpen"
      @toggle="togglePlanningDrawer"
      @add-marker="handleAddMarker"   
      @remove-marker="handleRemoveMarker"
      @show-analysis="$emit('show-analysis', $event)"
    />
  </div>
</template>

<script setup>
import { ref, nextTick , watch, onMounted, onUnmounted} from 'vue'
import SidebarHeader from './SideBarHeader.vue'
import FilterSection from './FilterSection.vue'
import SpotList from '../spots/SpotList.vue'
import PlanningDrawer from '../planningDrawer/PlanningDrawer.vue'
import { ElMessage } from 'element-plus'


const isSidebarOpen = ref(true)
const isPlanningDrawerOpen = ref(false)
const sidebarWidth = ref('400px')
const spotListRef = ref(null)
const filterSectionRef = ref(null)
const planningDrawerRef = ref(null)
const props = defineProps({mapRef: Object,mapLoaded: Boolean})
const sidebarRef = ref(null)
let resizeObserver = null
const isMapLoaded = ref(false)
const emit = defineEmits(['add-marker', 'remove-marker','show-analysis','spots-recommended'])

//控制侧边栏的开关
const toggleSidebar = () => {
  isSidebarOpen.value = !isSidebarOpen.value
  sidebarWidth.value = isSidebarOpen.value ? '400px' : '60px'
  
  if (!isSidebarOpen.value) {
    isPlanningDrawerOpen.value = false
  }
  
  // 等待过渡动画完成后再触发地图重新计算
  setTimeout(() => {
    props.mapRef?.recalculateWidth()
  }, 300) // 与CSS过渡时间相同
}

//控制规划抽屉的开关
const togglePlanningDrawer = () => {
  isPlanningDrawerOpen.value = !isPlanningDrawerOpen.value
}
const handleMapLoaded = () => {
  isMapLoaded.value = true
}

//处理筛选条件变化
const handleFilterChange = async (filterParams) => {
  try {
    await nextTick()
    if (spotListRef.value) {
      await spotListRef.value.handleFilterChange(filterParams)
    } else {
      console.error('SpotList 组件未找到')
      ElMessage.error('筛选失败，请刷新页面重试')
    }
  } catch (error) {
    console.error('筛选失败:', error)
    ElMessage.error('筛选失败，请稍后重试')
  }
}

//添加景点到规划抽屉
const addSpot = async (spot) => {
  // 确保规划抽屉是打开的
  if (!isPlanningDrawerOpen.value) {
    isPlanningDrawerOpen.value = true
  }
  
  // 等待 DOM 更新
  await nextTick()
  
  // 调用 PlanningDrawer 的 addSpot 方法
  planningDrawerRef.value?.addSpot(spot)
}

//搜索景点
const searchSpot = (spotName) => {
  if (filterSectionRef.value) {
    // 调用 FilterSection 的搜索方法
    filterSectionRef.value.searchSpot(spotName)
  }
}

const handleAddMarker = (spot) => {
  emit('add-marker', spot)  // 转发给父组件
}

const handleRemoveMarker = (attractionId) => {
  emit('remove-marker', attractionId)  // 转发给父组件
}

const handleSpotsRecommended = (spots) => {
  emit('spots-recommended', spots)  // 转发给父组件
}

const loadDefaultSpots = () => {
  spotListRef.value?.loadDefaultSpots()
}

const handleAutoImportSpots = (spots) => {
  // 确保规划抽屉打开
  if (!isPlanningDrawerOpen.value) {
    isPlanningDrawerOpen.value = true
  }
  
  // 等待DOM更新
  nextTick(() => {
    // 逐个添加景点到规划
    spots.forEach(spot => {
      planningDrawerRef.value?.addSpot(spot)
    })
  })
}

onMounted(() => {
  // 创建 ResizeObserver 实例
  resizeObserver = new ResizeObserver((entries) => {
    // 实时获取sidebar宽度变化并通知地图组件
    const width = entries[0].contentRect.width
    props.mapRef?.recalculateWidth()
  })

  // 开始观察
  if (sidebarRef.value) {
    resizeObserver.observe(sidebarRef.value)
  }

})

onUnmounted(() => {
  // 清理 observer
  if (resizeObserver) {
    resizeObserver.disconnect()
  }
})
defineExpose({
  searchSpot,
  planningDrawerRef,
  loadDefaultSpots
})
</script>

<style scoped>
.sidebar-wrapper {
  position: relative;
  height: 100%;
}

.sidebar {
  height: 100vh;
  overflow: hidden;
  transition: width 0.3s ease; /* 确保transition时间与setTimeout一致 */
  z-index: 200;
  position: relative;
  background-color: #f5f5f5;
}

.sidebar-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
}

.sidebar-closed {
  background-color: #f5f5f5;
  cursor: pointer;
  
  &:hover {
    background-color: #e4e7ed;
  }
}

.sidebar-main {
  padding: 20px;
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  opacity: 1;
  transition: opacity 0.3s ease;
}

.sidebar-closed .sidebar-main {
  opacity: 0;
}
</style>